import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; // 引入 pull_to_refresh 包
import '../../services/home_info_manager.dart';
import '../homeView/home_top_view.dart';
import '../homeView/home_recharge_view.dart';
import '../homeView/home_newplayer_view.dart';
import '../homeView/home_like_view.dart';
import '../homeView/home_hot_view.dart';
import '../homeController/search_page.dart';
import '../homeController/search_detail_page.dart';
import '../../class/controller/product_detail.dart';
import '../../l10n/app_localizations.dart';
import '../../login/controller/regis_view.dart';
import '../../manger/user_manger.dart';
import 'package:flutter/services.dart';
import '../../services/yh_info_manger.dart';
import '../../services/message_manger.dart';
import '../../services/global_state.dart';
import 'package:provider/provider.dart';
import '../homeView/home_order_pop.dart';
import '../../manger/network_utils.dart';
import '../../models/order_detail_model.dart';
import '../../services/number_utils.dart';
import '../homeView/home_coupon_pop.dart';
import '../../order/controller/order_pay.dart';
import '../../order/controller/order_detail.dart';
import 'dart:async';
import '../../mine/controller/mycoupon_page.dart';
import '../../services/version_manger.dart';
import '../../mine/view/newversion_view.dart';
import '../../manger/qysdk_manger.dart';
import '../../manger/umevent_utils.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final RefreshController _refreshController = RefreshController(initialRefresh: false);
  final HomeInfoManager homeManager = HomeInfoManager();
  final UserInfos userManger = UserInfos.shared;
  DateTime? _lastBackPressed;
  int numberCoupon = 0;
  Timer? _debounceTimer;

  @override
  void initState() {
    super.initState();
    userManger.onRefreshCallback = _onRefresh;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadCouponData();
    });
    checkVersion();
    UmengEvent.trackEvent("home_launch","进入首页","");

  }

  void checkVersion() {
    // TODO: 实现版本检查逻辑
    GetVersionManager.shared.getNewVersion((reminderType, isShow) async {
      if (reminderType == 0 && isShow) {
        final savedVersion = await VersionManager.getShownVersion();
        if (savedVersion != GetVersionManager.shared.newModel!.version) {
          showDialog(
            context: context,
            barrierDismissible: false,
            builder: (_) => NewVersionView(model: GetVersionManager.shared.newModel!),
          );
        }
      }
    });

  }

  @override
  void dispose() {
    userManger.onRefreshCallback = null;
    _debounceTimer?.cancel();
    super.dispose();
  }

  // 刷新数据方法
  Future<void> _onRefresh() async {
    await homeManager.loadInfoData();
    await homeManager.loadInitData();

    _loadCouponData();
    if (mounted) {
      setState(() {}); // 强制刷新UI
    }
  }

  Future<void> _loadCouponData() async {
    if (_debounceTimer?.isActive ?? false) {
      return; // 如果计时器还在运行，直接返回
    }
  
    final result = await MyCouponManger().loadDiscountData(0);
    if (result.success) {
      numberCoupon = result.myCoupon!.length;
      Provider.of<GlobalState>(context, listen: false).updateNotificationCount(result.myCoupon!.length);
    }

    final manager = MeassageInfoManager();
    final success = await manager.loadInfoData();
    if (success.success) {
        int countTotal = 0;
        if (success.msgListModel != null) {
          for (var model in success.msgListModel!) {
            countTotal += model.count;
          }
        }
      Provider.of<GlobalState>(context, listen: false).updateMessageCount(countTotal);
    } 

    loadPayWiter();
    _refreshController.refreshCompleted(); // 刷新完成

    // 设置5秒的计时器
    _debounceTimer = Timer(const Duration(seconds: 5), () {
      _debounceTimer = null;
    });
  }

  void loadPayWiter() async {
    final result = await checkIfTimestampExceededOneHour();
    if (!result) {
      showppp();
    }else{
      try {
        final response = await NetworkUtils.post(
          RequestCmd.waitPayment, 
          body: {},
        );
        final model = OrderHomeModel.fromJson(response);
        if (model.code == 200) {
          if (model.data!= null) {
            loadOrderData(model.data!.orderId);
          }
        } else {
          showppp();
        }
      } catch (e) {
        showppp();
      }
    }

  }

  void loadOrderData(String orderId) async {
    try {
      final response = await NetworkUtils.post(
        RequestCmd.detail,
        body: {'orderId': orderId},
      );
      final model = OrderDetailModel.fromJson(response); 
      if (model.code == 200) {
        if (model.data!= null && mounted) {
          showDialog(
            context: context,
            barrierDismissible: true, // 点击背景关闭弹窗
            builder: (BuildContext context) {
              return OrderPopView(
                gotoDetail: (orderId) {
                  Navigator.of(context).pop();
                  saveCurrentTimestamp();

                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => OrderDetailPage(orderId: orderId),
                    ),
                  );
                },
                gotoShouyitai: (orderId) {
                  saveCurrentTimestamp();
                  Navigator.of(context).pop();
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => OrderPayPage(orderId: orderId, spuId: model.data!.spuId),
                    ),
                  );
                },
                close: () {
                  saveCurrentTimestamp();
                  Navigator.of(context).pop();                  
                },
                order: model.data!,
              ); 
            },
          );         
              
        }
      } else {
        showppp();
      }
    } catch (e) {
      showppp();
    }
  }

  void _navigateToProductDetail(BuildContext context, int spuId) {
    UmengEvent.trackEvent("home_goods_click","首页点击商品进入详情页","");
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ProductDetailPage(
          spuId: spuId,
        ),
      ),
    );
  }

  void showppp() async{
    final result = await checkIfTimestampExceededOneDay();
    if (!result) {
      return;
    }

    if (numberCoupon > 0 && mounted) {
      showDialog(
        context: context,
        barrierDismissible: true, // 点击背景关闭弹窗
        builder: (BuildContext dialogContext) {
          return OcouponPopView(
            close: () {
              saveCurrentTimestamp2();
              Navigator.of(dialogContext).pop(); 
            },
            onCouponPress: () {
              saveCurrentTimestamp2();
              Navigator.of(dialogContext).pop(); 
              pushMyConpont();
            },
          );
        },
      );
    }
  }

  void pushMyConpont() {
    if (mounted) {  // 确保页面仍然有效
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => const MyCouponPage(),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final hotSearchList = homeManager.homeInitModel?.hotSearchList ?? [];

    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) async {
        DateTime now = DateTime.now();
        if (_lastBackPressed == null ||
            now.difference(_lastBackPressed!) > Duration(seconds: 2)) {
          _lastBackPressed = now;

          // 用 ScaffoldMessenger 显示 SnackBar 替代 toast
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('再按一次退出 App'),
              duration: Duration(seconds: 2),
            ),
          );
        } else {
          // 真正退出应用
          // 对于 Android 生效；iOS 通常无退出需求
          Future.delayed(Duration(milliseconds: 100), () {
            // 系统调用退出应用（仅限 Android）
            SystemNavigator.pop();
          });
        }
      },
      child: Scaffold(
      body: SmartRefresher(
        controller: _refreshController,  // 绑定刷新控制器
        onRefresh: _onRefresh,  // 设置下拉刷新的回调
        enablePullDown: true, 
        header: WaterDropHeader(
          complete: Text(AppLocalizations.of(context)!.pullToRefresh),
          refresh: Text(AppLocalizations.of(context)!.loading),
        ), // 启用下拉刷新
        child: SingleChildScrollView(
          child: Stack(
            children: [
              // 原有的 Column 布局
              Column(
                children: [
                  HomeTopView(
                    searchList: hotSearchList,
                    homeAdInfo: homeManager.homeInfoModel?.adList ?? [],
                    onAdTap: (id) {
                      _navigateToProductDetail(context, id);
                    },
                    onSearchAction: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => const SearchPage()),
                      );
                    },
                    onSearchKey: (key) {
                      // 点击热搜按钮
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => SearchDetailPage(serachKey: key)),
                      );
                    },
                    onContact: () async{
                      UmengEvent.trackEvent("home_kefu","首页点击客服","");
                      QYSDK.showQYSession();
                    },
                  ),
                  const SizedBox(height: 20),
                  HomeRechargeView(
                    rechargeList: homeManager.homeInfoModel?.rechargeList?? [],
                    onSubItemTap: (index) {
                      // 点击充值按钮
                      _navigateToProductDetail(context, index);
                    }
                  ),
                  const SizedBox(height: 20),
                  HomeNewPlayView(
                    newList: homeManager.homeInfoModel?.newList?? [],
                    onPlayPushDetail: (subId) {
                      _navigateToProductDetail(context, subId);
                    },
                  ),
                  const SizedBox(height: 20),
                  HomeLikeView(
                    likeList: homeManager.homeInfoModel?.likeList?? [],
                    onLikeItemTap: (itemId) {
                      // 处理喜欢项点击事件
                      _navigateToProductDetail(context, itemId);
                    }
                  ),
                  const SizedBox(height: 20),
                  HomeHotView(
                    hotCategoryList: homeManager.homeInfoModel?.hotCategoryList ?? [],
                    onItemTap: (itemId) {
                        _navigateToProductDetail(context, itemId);
                    },
                  ),
                  const SizedBox(height: 20),
                ],
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: !UserInfos.shared.token.isNotEmpty ? Container(
        height: 45,
        width: MediaQuery.of(context).size.width,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Color(0xFFFF9A66), Color(0xFFFF5E63)],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
        ),
        child: Row(
          children: [
            Padding(
              padding: EdgeInsets.only(left: 15, top: 5),
              child: Image.asset(
                'assets/images/group.png',
                width: 35,
                height: 35,
              ),
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 5),
                child: Text(
                  '${isChineseLocale() ? AppLocalizations.of(context)!.newUserBonus + AppLocalizations.of(context)!.welcomeBonus : AppLocalizations.of(context)!.newUserBonus + '\n     ' + AppLocalizations.of(context)!.welcomeBonus}',
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 14,
                  ),
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                UmengEvent.trackEvent("home_newmember_banner","首页点击新人福利条","");
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => RegisView(),
                  ),
                );
              },
              child: Container(
                margin: EdgeInsets.only(right: 15),
                width: 70,
                height: 35,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(17),
                ),
                child: Center(
                  child: Text(
                    AppLocalizations.of(context)!.signUp,
                    style: TextStyle(
                      color: Color(0xFFF04349),
                      fontWeight: FontWeight.bold,
                      fontSize: 15,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ): Container(height: 5,),
    ),
    );
  }
}
